package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import com.app.aspect.AutoLog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.app.mapper.TenantRelationshipMapper;
import com.app.model.TenantRelationship;
import com.app.model.Yonghu;
import com.app.service.IYonghuService;
import com.app.util.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-02-27
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/yonghu")
public class YonghuController {

    @Autowired
    private IYonghuService yonghuService;

    @Autowired
    private TenantRelationshipMapper tenantRelationshipMapper;

    @PostMapping("/applet/updateYonghu")
    public Result updateYonghu(HttpServletRequest request, @Param("yonghu") Yonghu yonghu) {

        String token = request.getHeader("token");
        String userId = StpUtil.getLoginIdByToken(token).toString();

        if (yonghu.getId() == null) {
            yonghuService.save(yonghu);
        } else {
            yonghuService.updateById(yonghu);
        }

        return Result.success("操作成功！");
    }

    @ApiOperation(value = "管理后台-租户管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "page", value = "页", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "limit", value = "条", required = true, dataType = "Integer"),
    })
    @GetMapping("/admin/tenantList")
    public Result tenantList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                             String name) {
        Page<Yonghu> fwPage = new Page<>(page, limit);
        return Result.success(this.yonghuService.adminPage(fwPage, name));
    }

    /**
     * 新增或编辑租户
     *
     * @param yonghu 租户对象
     * @return 操作结果
     */
    @ApiOperation(value = "新增或编辑租户")
    @PostMapping("/admin/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Yonghu yonghu) {
        try {
            // 输入验证
            if (yonghu == null) {
                return Result.error("租户对象无效");
            }

            boolean savedOrUpdated;
            if (yonghu.getId() != null) {
                savedOrUpdated = this.yonghuService.updateById(yonghu);
            } else {
                savedOrUpdated = this.yonghuService.save(yonghu);
            }

            if (savedOrUpdated) {
                return Result.success("租户保存或更新成功");
            } else {
                return Result.error("租户保存或更新失败");
            }
        } catch (Exception e) {
            return Result.error("系统错误，请稍后再试");
        }
    }

    /**
     * 删除租户
     *
     * @param id 租户ID
     * @return 操作结果
     */
    @ApiOperation(value = "删除租户")
    @GetMapping("/delete")
    public Result delete(Integer id) {
        try {
            // 获取租户
            Yonghu yonghu = this.yonghuService.getById(id);
            if (yonghu == null) {
                return Result.error("该租户不存在");
            }

            // 设置删除标志并更新
            yonghu.setIsDel(1);
            boolean updateSuccess = this.yonghuService.updateById(yonghu);

            if (updateSuccess) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败，请稍后再试");
            }
        } catch (Exception e) {
            return Result.error("系统错误，请稍后再试");
        }
    }

    @ApiOperation(value = "同步承租人关系记录信息", notes = "同步承租人关系记录信息")
    @GetMapping("/dataMigration")
    public void dataMigration(){
        QueryWrapper<Yonghu> queryWrapper = new QueryWrapper<>();
        List<Yonghu> yonghus = yonghuService.list(queryWrapper);
        for (Yonghu yonghu : yonghus){

            //第一承租人
            TenantRelationship tenantRelationship = new TenantRelationship();
            tenantRelationship.setUniqueId(yonghu.getUniqueId());
            tenantRelationship.setLeaseCertificateNumber(yonghu.getLeaseCertificateNumber()+"");
            tenantRelationship.setTenantSerialNumber(1);
            tenantRelationship.setTenantName(yonghu.getFirstTenantName());
            tenantRelationship.setTenantCompany(yonghu.getFirstTenantCompany());
            tenantRelationship.setTenantIdCard(yonghu.getFirstTenantIdCard());
            tenantRelationship.setTenantPhone(yonghu.getFirstTenantPhone());
            tenantRelationship.setLeaseRelationshipTime(yonghu.getLeaseRelationshipTimeOne());
            tenantRelationship.setDepositPaid(yonghu.getDepositPaidOne());
            tenantRelationship.setPaymentTime(yonghu.getPaymentTimeOne());
            tenantRelationship.setDepositReturned(yonghu.getDepositReturnedOne());
            tenantRelationship.setReturnTime(yonghu.getReturnTimeOne());
            tenantRelationship.setExcessAreaRent(yonghu.getExcessAreaRent());
            tenantRelationship.setPolicyReduction(yonghu.getPolicyReduction());
            tenantRelationship.setTotalMonthlyRent(yonghu.getTotalMonthlyRent());
            tenantRelationship.setOtherVariable(yonghu.getOtherVariable());
            tenantRelationship.setBasementVariable(yonghu.getBasementVariable());
            tenantRelationship.setLiveStatus(yonghu.getLiveStatus());


            //组装家庭成员
            JSONArray array = new JSONArray();

            String family_member_name_one = yonghu.getFamilyMemberNameOne();
            String family_member_name_two = yonghu.getFamilyMemberNameTwo();
            String family_member_name_three = yonghu.getFamilyMemberNameThree();
            String family_member_name_four = yonghu.getFamilyMemberNameFour();

            String family_member_relationship_one = yonghu.getFamilyMemberRelationshipOne();
            String family_member_relationship_two = yonghu.getFamilyMemberRelationshipTwo();
            String family_member_relationship_three = yonghu.getFamilyMemberRelationshipThree();
            String family_member_relationship_four = yonghu.getFamilyMemberRelationshipFour();

            String family_member_company_one = yonghu.getFamilyMemberCompanyOne();
            String family_member_company_two = yonghu.getFamilyMemberCompanyTwo();
            String family_member_company_three = yonghu.getFamilyMemberCompanyThree();
            String family_member_company_four = yonghu.getFamilyMemberCompanyFour();

            JSONObject family_member_one = new JSONObject();
            family_member_one.put("name", family_member_name_one);
            family_member_one.put("relationship", family_member_relationship_one);
            family_member_one.put("company", family_member_company_one);
            family_member_one.put("isContact", 0);

            JSONObject family_member_two = new JSONObject();
            family_member_two.put("name", family_member_name_two);
            family_member_two.put("relationship", family_member_relationship_two);
            family_member_two.put("company", family_member_company_two);
            family_member_two.put("isContact", 0);

            JSONObject family_member_three = new JSONObject();
            family_member_three.put("name", family_member_name_three);
            family_member_three.put("relationship", family_member_relationship_three);
            family_member_three.put("company", family_member_company_three);
            family_member_three.put("isContact", 0);

            JSONObject family_member_four = new JSONObject();
            family_member_four.put("name", family_member_name_four);
            family_member_four.put("relationship", family_member_relationship_four);
            family_member_four.put("company", family_member_company_four);
            family_member_four.put("isContact", 0);
            if (family_member_name_one != null){
                array.add(family_member_one);
            }
            if (family_member_name_two != null){
                array.add(family_member_two);
            }
            if (family_member_name_three != null){
                array.add(family_member_three);
            }
            if (family_member_name_four != null){
                array.add(family_member_four);
            }


            //第二承租人
            if (yonghu.getSecondTenantName()!= null){
                TenantRelationship tenantRelationship2 = new TenantRelationship();
                tenantRelationship2.setUniqueId(yonghu.getUniqueId());
                tenantRelationship2.setLeaseCertificateNumber(yonghu.getLeaseCertificateNumber()+"");
                tenantRelationship2.setTenantSerialNumber(2);
                tenantRelationship2.setTenantName(yonghu.getSecondTenantName());
                tenantRelationship2.setTenantCompany(yonghu.getSecondTenantCompany());
                tenantRelationship2.setTenantIdCard(yonghu.getSecondTenantIdCard());
                tenantRelationship2.setTenantPhone(yonghu.getSecondTenantPhone());
                tenantRelationship2.setLeaseRelationshipTime(yonghu.getLeaseRelationshipTimeTwo());
                tenantRelationship2.setDepositPaid(yonghu.getDepositPaidTwo());
                tenantRelationship2.setPaymentTime(yonghu.getPaymentTimeTwo());
                tenantRelationship2.setDepositReturned(yonghu.getDepositReturnedTwo());
                tenantRelationship2.setReturnTime(yonghu.getReturnTimeTwo());
                tenantRelationship2.setExcessAreaRent(yonghu.getExcessAreaRent());
                tenantRelationship2.setPolicyReduction(yonghu.getPolicyReduction());
                tenantRelationship2.setTotalMonthlyRent(yonghu.getTotalMonthlyRent());
                tenantRelationship2.setOtherVariable(yonghu.getOtherVariable());
                tenantRelationship2.setBasementVariable(yonghu.getBasementVariable());
                tenantRelationship2.setLiveStatus(yonghu.getLiveStatus());

                if (array.size() > 0){
                    tenantRelationship2.setFamilyMembersJson(array.toJSONString());
                }
                tenantRelationshipMapper.insert(tenantRelationship2);

            }

            if (array.size() > 0){
                tenantRelationship.setFamilyMembersJson(array.toJSONString());
            }

            tenantRelationshipMapper.insert(tenantRelationship);


        }
    }

}

